/*
 ============================================================================
 Name		: WidgetInstaller.cpp
 Author	  : Nokia
 Copyright   : 
 Description : Exe source file
 ============================================================================
 */

//  Include Files  

#include <e32base.h>
#include <e32std.h>
#include <SWInstApi.h>
#include <SWInstDefs.h>
#include <f32file.h>
#include <aknutils.h>
#include "WgzInstaller.h"


static const TSecureId KInstallerSID = 0x101F875A;
_LIT( KWidgetInstallerDir, "d:\\WgzInstaller\\" );

//TODO: Use your widget name here 
_LIT( KWidgetInstallerFileName, "buycatalog.wgz" );


LOCAL_C TBool isProcessRunning()
{
	TFullName res;
  	TFindProcess find;

  	while( find.Next( res ) == KErrNone )
    {
      	RProcess ph;
      	if (ph.Open( find ) != KErrNone)
      		continue;

		TSecureId secId = ph.SecureId();
      	ph.Close();
      	
      	if (secId == KInstallerSID)
      		return ETrue;
    }
  	
  	return EFalse;
}


LOCAL_C TInt getPath( TDes& path ){

	RFs iFileSession;
    TInt err = iFileSession.Connect();
    if (err != KErrNone)
    	return err;
   
    //Read the name of the widget package
    TFileName widgetFileName;
    
    widgetFileName.Append(KWidgetInstallerDir);
    widgetFileName.Append(KWidgetInstallerFileName);
    
    path.Copy(widgetFileName);
  
    TFindFile findFile(iFileSession);
    findFile.FindByDir(path,KNullDesC);
    
    path =  findFile.File();
    iFileSession.Close();
    
    return KErrNone;
}


//  Global Variables
GLDEF_C TInt E32Main()
	{
	// Create cleanup stack
	__UHEAP_MARK;
	CTrapCleanup* cleanup = CTrapCleanup::New();
	
	// get wgz path
	TFileName path;
	getPath( path );

	//wait while process installer doesn't stop running
	while( isProcessRunning() ) {
		User::After( 1000000 ); // put thread to sleep for 1 second
	}
	
	SwiUI::RSWInstLauncher iLauncher; 
	
	if (iLauncher.Connect() == KErrNone)
	{
		iLauncher.Install( path );
		iLauncher.Close();
	}
	
	//Now we can delete the directory with the temp installation files to free up memory
	RFs iFileSession;
	iFileSession.Connect();
	CFileMan* fileMan;
	TRAPD(err, fileMan = CFileMan::NewL(iFileSession));
	if(!err) 
	    {
	    fileMan->RmDir(KWidgetInstallerDir);
	    delete fileMan;    
	    }
    
	iFileSession.Close();   	
	
	delete cleanup;
	
	__UHEAP_MARKEND;
	return err;
	}

